import os
# pip install reportlab
import time

from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, PageBreak, Table, TableStyle
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet, LineStyle
from reportlab.lib.units import mm
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

# 字体引用，中文
pdfmetrics.registerFont(TTFont('ukai', 'ukai.ttc'))
pdfmetrics.registerFont(TTFont('uming', 'uming.ttc'))


class PDFManager(object):
    """
    pdf管理器

    pdfkit
        wkhtmltopdf主要用于HTML生成PDF。
        pdfkit是基于wkhtmltopdf的python封装，支持URL，本地文件，文本内容到PDF的转换，其最终还是调用wkhtmltopdf命令。是目前接触到的python生成pdf效果较好的。
        使用方法
            brew cask install wkhtmltopdf
        安装pdfkit
            pip install pdfkit
        使用
            import pdfkit

    reportlab
        从零开始制作PDF文档
        安装
            pip install reportlab
        使用
            from reportlab.pdfgen import canvas
    """

    def __init__(self, file_name):
        self.file_name = file_name + ".pdf"

    @staticmethod
    def hello():

        from reportlab.pdfgen import canvas
        c = canvas.Canvas("/helloworld.pdf")
        print(c.__dict__)
        c.drawString(100, 100, "Hello,World")
        c.showPage()
        c.save()

    @staticmethod
    def get_pdf_page_num(file_path):
        from PyPDF2 import PdfFileReader, PdfFileWriter
        with open(file_path, "rb") as file:
            doc = PdfFileReader(file)
            page_count = doc.getNumPages()
        return page_count

    def get_title_style(self, title_Level=None):
        """
        根据标题序号，获取相应的样式
        :param title_Level:
        :return:
        """
        name = "TitleStyle"
        font_size = 30
        alignment = TA_CENTER
        if title_Level == 1:
            name += str(title_Level)
            font_size = 26
            alignment = TA_LEFT
        elif title_Level == 2:
            name += str(title_Level)
            font_size = 20
            alignment = TA_LEFT

        return ParagraphStyle(name=name, fontName="ukai", fontSize=font_size, alignment=alignment)

    # @staticmethod
    def pdf_creation(self, file_name: str, storage_path=None):
        """
        PDF生成
        :return:
        """
        file_path = pdf_name = file_name + "-检测报告.pdf"
        if storage_path:
            file_path = os.path.join(storage_path, pdf_name)
        # 格式
        title_style = ParagraphStyle(name="TitleStyle", fontName="uming", fontSize=24, alignment=TA_CENTER)
        content_style = ParagraphStyle(name="ContentStyle", fontName="ukai", fontSize=14, alignment=TA_LEFT)
        product_info_table_style = TableStyle([('FONTNAME', (0, 0), (-1, -1), 'ukai'),
                                               ('FONTSIZE', (0, 0), (-1, -1), 12),
                                               ('FONTSIZE', (0, 0), (0, 3), 13),
                                               ('FONTSIZE', (2, 0), (2, 3), 13),
                                               ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                                               ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                                               ('BOTTOMPADDING', (0, 0), (-1, -1), 4),
                                               ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
                                               ])
        result_info_style = [('FONTNAME', (0, 0), (-1, -1), 'ukai'),
                             ('FONTSIZE', (0, 0), (-1, -1), 12),
                             ('FONTSIZE', (0, 0), (0, 3), 13),
                             ('FONTSIZE', (2, 0), (2, 3), 13),
                             ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                             ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                             ('BOTTOMPADDING', (0, 0), (-1, -1), 4),
                             ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
                             ('SPAN', (1, 3), (3, 3)),
                             ]
        if True:
            result_info_style.append(("BACKGROUND", (1, 1), (1, 1), colors.yellow))
        if True:
            result_info_style.append(("BACKGROUND", (1, 2), (1, 2), colors.yellow))
        if True:
            result_info_style.append(("BACKGROUND", (3, 1), (3, 1), colors.yellow))
        if True:
            result_info_style.append(("BACKGROUND", (3, 2), (3, 2), colors.yellow))
            result_info_style.append(("BACKGROUND", (1, 3), (3, 3), colors.yellow))

        result_info_table_style = TableStyle(result_info_style)
        colWidths = [40 * mm, 40 * mm, 40 * mm, 45 * mm]

        # 数据
        time_str = time.strftime("%Y-%m-%d %H:%M:%S")
        product_info_table_data = [['品种名称', "00000000000", '检测日期', time_str],
                                   ['生产批次', "11111111111", '托盘号', "2222222222"]]
        standard_info_table_data = [['短边范围', "7.0 - 8.0", '异形比范围', "3.6 - 4.4"],
                                    ['集中度下限', "50%", '异常异形比上限', "5%"]]
        result_info_table_data = [['样本量', "290", '标准差', "2.65", ],
                                  ['平均异形比', '3.75', '集中度', '85%'],
                                  ['平均短边', '7.512', '异常异形比比例', '6.5%'],
                                  ['判断结果', "不合格"]
                                  ]
        story = []
        story.append(Spacer(1, 10 * mm))
        story.append(Paragraph("异形纤维分析报告", title_style))
        story.append(Spacer(1, 12 * mm))
        story.append(Paragraph("一、	样品信息", content_style))
        story.append(Spacer(1, 5 * mm))
        product_info_table = Table(product_info_table_data, colWidths=colWidths, rowHeights=8 * mm,
                                   style=product_info_table_style)
        story.append(product_info_table)

        story.append(Spacer(1, 12 * mm))
        story.append(Paragraph("二、	检测标准", content_style))
        story.append(Spacer(1, 5 * mm))
        product_info_table = Table(standard_info_table_data, colWidths=colWidths, rowHeights=8 * mm,
                                   style=product_info_table_style)
        story.append(product_info_table)

        story.append(Spacer(1, 6 * mm))
        story.append(Paragraph("三、	检测结果", content_style))
        story.append(Spacer(1, 5 * mm))
        result_info_table = Table(result_info_table_data, colWidths=colWidths, rowHeights=8 * mm,
                                  style=result_info_table_style)
        story.append(result_info_table)
        story.append(Spacer(1, 5 * mm))
        # histogram_image = Image(histogram_path, width=500, height=375)
        # story.append(histogram_image)
        # local_img = transform_result["body"]["labelSet"][0].get("imagePath")

        # handle_image = self._shared_memory_manager.get_image(local_img)
        # handle_image_info = cv2.imencode(".png", handle_image)[1]
        # handle_image_io = io.BytesIO(handle_image_info.tobytes())
        # handle_image_pdf = Image(handle_image_io, width=500, height=375)
        # story.append(handle_image_pdf)
        doc = SimpleDocTemplate(file_path, leftMargin=20 * mm, rightMargin=20 * mm, topMargin=2 * mm,
                                bottomMargin=20 * mm)
        doc.build(story)
        print('...gen_pdf...exit')


if __name__ == '__main__':
    pdf_manager = PDFManager("dd")
    # pdf_manage.hello()
    pdf_manager.pdf_creation("33")
